package com.handpay.zztong.hp.setting.activity;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.swiper.landi.AipSharedPreferences;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.ZZTApplication;
import com.handpay.zztong.hp.base.callback.BusinessEngineListener;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.login.model.verifyversion.VerifyVersionBean;
import com.handpay.zztong.hp.login.model.verifyversion.VerifyVersionModel;
import com.handpay.zztong.hp.setting.model.versioninfo.VersionInfoBean;
import com.handpay.zztong.hp.setting.model.versioninfo.VersionInfoModel;

import java.util.Hashtable;

public class AboutActivity extends ZZTongActivity {

    private TextView clientName;
    private TextView versionNumber;
    private LinearLayout ll_version_update;
    private LinearLayout ll_currentVersion_instruction;
    private TextView versionTextView;
    private ImageView arrow;
    private String description;
    private String updateUrl;
    private String version, forcedUpdate;
    private VerifyVersionModel mVerifyVersionModel;


    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(this.getString(R.string.Version_center), true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mVerifyVersionModel = new VerifyVersionModel();
        this.setContentView(R.layout.activity_about);
        super.onCreate(savedInstanceState);
        clientName = (TextView) findViewById(R.id.app_client_name);
        clientName.setText(getResources().getString(R.string.app_name) + getResources().getString(R.string.vpos_client));
        versionNumber = (TextView) findViewById(R.id.current_version_number);
        versionTextView = (TextView) findViewById(R.id.tv_version_update_tip);
        ll_version_update = (LinearLayout) findViewById(R.id.ll_version_update);
        ll_currentVersion_instruction = (LinearLayout) findViewById(R.id.ll_Version_instruction);
        arrow = (ImageView) findViewById(R.id.arrow_tip);
        ll_currentVersion_instruction.setOnClickListener(this);
        versionNumber.setText(getResources().getString(R.string.current_version_number) + ClientEngine.VERSION);// ZZTConfig.testerVersion
        doVerifyVersion();
        initdata();
    }

    private void doVerifyVersion() {
        mVerifyVersionModel.doVerifyVersionPost(this, new BusinessEngineListener<VerifyVersionBean>() {
            @Override
            public void callbackBusinessResponse(VerifyVersionBean bean) {
                doVerifyVersionCallback(bean);
            }
        });
    }

    public void doVerifyVersionCallback(VerifyVersionBean bean) {
        if (null != bean.getDgTrade()) {
            if ("0".equals(bean.getDgTrade())) {
                ZZTConfig.DW_TRADE = false;
            } else if ("1".equals(bean.getDgTrade())) {
                ZZTConfig.DW_TRADE = true;
            }
        }
        ClientEngine.getInstance().saveGlobal(POLL_TIME, bean.getPollTime());
        String version = bean.getVersion();
        String url = bean.getUrl();
        String description = bean.getDescription();
        String forcedUpdate = bean.getForcedUpdate();
        ClientEngine.getInstance().saveGlobal(VERSION, version);
        ClientEngine.getInstance().saveGlobal(DESCRIPTION, description);
        ClientEngine.getInstance().saveGlobal(UPDATEURL, url);
        ClientEngine.getInstance().saveGlobal(FORCEDUPDATE, forcedUpdate);
        HPLog.i("jjyang", "version:" + version + " url:" + url + " description:" + description + " forcedUpdate:" + forcedUpdate);
        if (TextUtils.isEmpty(url) && TextUtils.isEmpty(description)) {
            return;
        } else {
            description = description.replace("&", "\n");
        }
        String title = getString(R.string.updatetitle, version);
        String message = description;
        int result = version.compareTo(ClientEngine.VERSION);
        if ("0".equals(forcedUpdate) && result > 0) {
            String mVersion = null;
            mVersion = AipSharedPreferences.getInstance(this).getVersion();
            HPLog.i("ZZTongActivity", "mVersion:" + mVersion);
            if (!TextUtils.isEmpty(mVersion) && version.equals(mVersion)) {
                return;
            } else {
                isforcedCheckVersion(this, title, message, url, version);
            }
        } else {
            checkVersion(this, title, message, url);
        }
    }

    /**
     * 版本检测处理流程
     *
     * @param activity
     * @param title
     * @param message
     * @param url
     * @param version
     */
    public void isforcedCheckVersion(final ZZTongActivity activity, String title, String message, final String url, final String version) {
        showAlertDialog(activity, title, message, false, getResources().getString(R.string.immediately_update), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    goToDownloadActivity(activity, url);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }, getResources().getString(R.string.not_update), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 暂时不更新，但用户可以进入应用，并使用功能
                dialog.dismiss();
                long currentTimeMillis = System.currentTimeMillis();
                AipSharedPreferences.getInstance(AboutActivity.this).setVerifyLastTime(currentTimeMillis);

            }
        }, getResources().getString(R.string.no_longer_remind), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int arg1) {
                // 用户同样可以进入应用，但是，下次检测版本的时候，如果是同一版本，不再提示，如果有更高版本，会再提示。
                AipSharedPreferences.getInstance(AboutActivity.this).setVersion(version);
                dialog.dismiss();
            }
        });
    }

    /***
     * 初始化版本检测相关数据
     */
    private void initdata() {
        version = (String) ClientEngine.getInstance().getGlobal(VERSION);
        description = (String) ClientEngine.getInstance().getGlobal(DESCRIPTION);
        updateUrl = (String) ClientEngine.getInstance().getGlobal(UPDATEURL);
        forcedUpdate = (String) ClientEngine.getInstance().getGlobal(FORCEDUPDATE);
        int result = version.compareTo(ClientEngine.VERSION);
        HPLog.d(HPLog.SSX_TAG, "版本比较结果:" + result);
        if (result < 0 || result == 0) {
            versionTextView.setText(getResources().getString(R.string.current_version_new));
            ll_version_update.setOnClickListener(null);
        } else {
            versionTextView.setText(getResources().getString(R.string.find_version_new));
            arrow.setVisibility(View.VISIBLE);
            arrow.setBackgroundResource(R.drawable.smallreddot);
            ll_version_update.setOnClickListener(this);
        }

    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected boolean isShownTabs() {
        return false;
    }


    /**
     * 版本检测处理流程
     */
    protected void isUpdateVersion(final ZZTongActivity activity, String title, String message, final String url) {
        showAlertDialog(activity, title, message, false, getResources().getString(R.string.immediately_update), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    // ClientEngine.getInstance().browse(activity, url,
                    // false);
                    goToDownloadActivity(activity, url);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }, getResources().getString(R.string.not_update), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }, null, null);
    }

    public void doVersionDesc() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("version", ClientEngine.VERSION);
        params.put("platform", ClientEngine.MOBILETYPE);
        params.put("channel", ZZTConfig.UPDATE_CHANNEL);
        new VersionInfoModel().doVersionInfoPost(this, params, new BusinessEngineListener<VersionInfoBean>() {
            @Override
            public void callbackBusinessResponse(VersionInfoBean versionInfoBean) {
                if (versionInfoBean.getResponseCode().equals("0")) {
                    Intent intent = new Intent(AboutActivity.this, VersionIntroductionActivity.class);
                    intent.putExtra("versionInfoBean", versionInfoBean);
                    startActivity(intent);
                } else {
                    showAlertDialog(AboutActivity.this, getString(R.string.prompt), versionInfoBean.getErrMessage());
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.ll_version_update) {
            String message = description;
            String title = getString(R.string.updatetitle, version);
            if ("0".equals(forcedUpdate)) {
                isUpdateVersion(AboutActivity.this, title, message, updateUrl);
            } else {
                checkVersion(AboutActivity.this, title, message, updateUrl);
            }
        } else if (i == R.id.ll_Version_instruction) {
            doVersionDesc();
        }
    }


}
